/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package master;

import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import produto.Produto;
import produto.ProdutoDao;
import util.Util;

/**
 *
 * @author Camilo
 */
public class JdPesquisaProd extends javax.swing.JDialog {
//  Define o model da tabela

  PesquisaTableModel ptm = new PesquisaTableModel();
  List<Produto> lstProd;
  private Master master;

  /**
   * Creates new form JdPesquisaProd
   */
  public JdPesquisaProd(Master jmaster, boolean modal) {
    super(jmaster, modal);
    initComponents();
    this.master = jmaster;
    Integer r = master.jtNfeItens.getSelectedRow();
    jtfBarras.setText(master.jtNfeItens.getValueAt(r, 2).toString());
    
    setLocationRelativeTo(master); // centraliza o jDialog
//    define o ícone para a janela
    ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource("imagens/icon_advancedSearch.png"));
    this.setIconImage(icon.getImage());
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this
   * code. The content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jtfDescricao = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jtfBarras = new javax.swing.JTextField();
    jbBuscar = new javax.swing.JButton();
    jbSelecionar = new javax.swing.JButton();
    jbCancelar = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtProd = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Pesquisa de produtos");

    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Critérios da Pesquisa"));

    jLabel1.setText("Descrição:");

    jtfDescricao.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfDescricaoFocusGained(evt);
      }
    });
    jtfDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfDescricaoKeyPressed(evt);
      }
    });

    jLabel2.setText("Barras:");

    jtfBarras.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfBarrasFocusGained(evt);
      }
    });
    jtfBarras.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfBarrasKeyPressed(evt);
      }
    });

    jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/pesquisa.png"))); // NOI18N
    jbBuscar.setMnemonic('b');
    jbBuscar.setText("Buscar");
    jbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbBuscarActionPerformed(evt);
      }
    });

    jbSelecionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/task-complete.png"))); // NOI18N
    jbSelecionar.setMnemonic('s');
    jbSelecionar.setText("Selecionar");
    jbSelecionar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbSelecionarActionPerformed(evt);
      }
    });

    jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/task-reject.png"))); // NOI18N
    jbCancelar.setMnemonic('c');
    jbCancelar.setText("Cancelar");
    jbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbCancelarActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel1)
          .addComponent(jtfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 433, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel2)
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(1, 1, 1)
            .addComponent(jtfBarras, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jbBuscar)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jbSelecionar)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jbCancelar))))
    );

    jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbBuscar, jbCancelar, jbSelecionar});

    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addGap(2, 2, 2)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(jLabel2))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jtfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfBarras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jbBuscar)
          .addComponent(jbSelecionar)
          .addComponent(jbCancelar))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jtProd.setModel(ptm);
    /**Desabilita o ajuste automático da largura das colunas*/
    jtProd.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    /** ajusta a largura das colunas*/
    jtProd.getColumnModel().getColumn(0).setPreferredWidth(60);//cod
    jtProd.getColumnModel().getColumn(1).setPreferredWidth(110); //barras
    jtProd.getColumnModel().getColumn(2).setPreferredWidth(500); //descricao
    jtProd.getColumnModel().getColumn(3).setPreferredWidth(100); //custo
    jtProd.getColumnModel().getColumn(4).setPreferredWidth(100); //preço
    jtProd.getColumnModel().getColumn(5).setPreferredWidth(100); // estoque
    jtProd.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtProdKeyPressed(evt);
      }
    });
    jScrollPane1.setViewportView(jtProd);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jScrollPane1)
          .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 967, Short.MAX_VALUE))
        .addGap(0, 11, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(0, 12, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void jtfDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDescricaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      try {
        buscaProdutoPDesc();
      } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
      encerrar();
    }
  }//GEN-LAST:event_jtfDescricaoKeyPressed

  private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed
    try {
      buscaProdutoPDesc();
      jtfDescricao.requestFocus();
    } catch (SQLException e) {
      JOptionPane.showMessageDialog(null, e.getMessage());
    }
  }//GEN-LAST:event_jbBuscarActionPerformed

  private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
    encerrar();
  }//GEN-LAST:event_jbCancelarActionPerformed

  private void jtProdKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtProdKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      selecionaProduto();
    } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
      encerrar();
    }
  }//GEN-LAST:event_jtProdKeyPressed

  private void jbSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSelecionarActionPerformed
    selecionaProduto();
  }//GEN-LAST:event_jbSelecionarActionPerformed

  private void jtfBarrasKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfBarrasKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        buscaProdutoPBar();
    } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
      encerrar();
    }
  }//GEN-LAST:event_jtfBarrasKeyPressed

  private void jtfBarrasFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfBarrasFocusGained
    new Util().selJtf(jtfBarras);
  }//GEN-LAST:event_jtfBarrasFocusGained

  private void jtfDescricaoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfDescricaoFocusGained
    new Util().selJtf(jtfDescricao);
  }//GEN-LAST:event_jtfDescricaoFocusGained

  private void selecionaProduto() {
    Integer r = master.jtNfeItens.getSelectedRow();
    Integer prod = Integer.parseInt(jtProd.getValueAt(jtProd.getSelectedRow(), 0).toString());
    String barras = jtProd.getValueAt(jtProd.getSelectedRow(), 1).toString();
    master.jtNfeItens.setValueAt(prod, r, 1);
    master.jtNfeItens.setValueAt(barras, r, 2);
    encerrar();
  }

  private void buscaProdutoPDesc() throws SQLException {
    ProdutoDao pdao = new ProdutoDao();
    setJtProdTM(lstProd = pdao.getListaDesc(jtfDescricao.getText()));
  }

  private void buscaProdutoPBar() {
    try {
    ProdutoDao pdao = new ProdutoDao();
    setJtProdTM(lstProd = pdao.getListaBarras(jtfBarras.getText()));
    } catch (SQLException e){
      JOptionPane.showMessageDialog(null, e.getMessage());
    }
  }
  
  private void setJtProdTM(List<Produto> produto) {
    while (ptm.getRowCount() > 0) {
      ptm.remove(0);
    }
    if (produto.isEmpty()) {
      JOptionPane.showMessageDialog(null, "Nenhum registro encontrado!",
              "ATENÇÃO", JOptionPane.ERROR_MESSAGE);
    } else {
      ptm.adicionaLista(produto);
    }
  }

  private void encerrar() {
    this.dispose();
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(JdPesquisaProd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        JdPesquisaProd dialog = new JdPesquisaProd(new Master(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JButton jbBuscar;
  private javax.swing.JButton jbCancelar;
  private javax.swing.JButton jbSelecionar;
  private javax.swing.JTable jtProd;
  private javax.swing.JTextField jtfBarras;
  private javax.swing.JTextField jtfDescricao;
  // End of variables declaration//GEN-END:variables
}
